package com.glasses.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.glasses.dao.TicketDao;
import com.glasses.entity.Ticket;
import com.glasses.orm.base.Ex.BaseServiceEx;
import com.glasses.orm.dictionary.TicketStatus;
import com.glasses.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wangchao.tools.CreateKey;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ashin on 2018/10/11.
 */

@Service
public class TicketServiceImp extends BaseServiceEx implements TicketService {

    @Autowired
    TicketDao ticketDao;

    @Override
    public void init() {
        super.init(ticketDao);
    }

    @Override
    public JSONObject generate(Map map) throws Exception {
        int num = toInt(map.get("num").toString());
        List<Map> ticketList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            Map ticket = new HashMap();
            ticket.put("cardNum", CreateKey.getRandomString(10));
            ticket.put("status", 0);
            ticket.put("price", map.get("price"));
            ticket.put("info", map.get("info"));
            ticket.put("title", map.get("title"));
            ticket.put("endTime", map.get("endTime"));
            ticket.put("type", map.get("type"));
            ticketList.add(ticket);
        }

        int ret = ticketDao.insertListTp(ticketList);
        if (ret == -1)
            return this.codeMess(eCode, "新增失败");
        return this.codeMess(sCode, "新增成功");
    }

    @Override
    public JSONObject getTicket(Map map) throws Exception {
        Ticket ticket = ticketDao.selectp(map);
        if (ticket == null) {
            return this.codeMess(eCode, "券码有误,请检查重新输入");
        }
        if (String.valueOf(TicketStatus.已使用).equals(ticket.getStatus())) {
            return this.codeMess(eCode, "当前券码已使用");
        }
        if (String.valueOf(TicketStatus.待使用).equals(ticket.getStatus())) {
            return this.codeMess(eCode, "当前券码已被领取");
        }
        return this.codeData(ticket);
    }

    @Override
    public JSONObject receiveTicket(Map map) throws Exception {
        Map ticketMap = new HashMap();
        ticketMap.put("cardNum", map.get("cardNum"));
        JSONObject ticket = this.getTicket(ticketMap);
        if (ticket.getInteger("code") == eCode) {
            return ticket;
        }
        map.put("status", String.valueOf(TicketStatus.待使用));
        int ret = ticketDao.updatep(map);
        if (ret == -1) {
            return this.codeMess(eCode, "领取卡券失败");
        }
        return this.codeMess(sCode, "领取卡券成功");
    }
}
